package com.xqboss.framework.web.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.*;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.enums.UserStatus;
import com.xqboss.common.utils.uuid.InvitCodeUtil;
import com.xqboss.common.utils.sms.SmsUtil;
import com.xqboss.framework.manager.AsyncManager;
import com.xqboss.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.constant.Constants;
import com.xqboss.common.constant.UserConstants;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.domain.model.RegisterBody;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.exception.user.CaptchaException;
import com.xqboss.common.exception.user.CaptchaExpireException;
import com.xqboss.common.utils.MessageUtils;
import com.xqboss.common.utils.SecurityUtils;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.framework.manager.factory.AsyncFactory;
import com.xqboss.system.service.ISysConfigService;
import com.xqboss.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 控制台-注册
     */
//    public String register(RegisterBody registerBody) {
//        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
//        SysUser sysUser = new SysUser();
//        sysUser.setUserName(username);
//
//        // 验证码开关
//        boolean captchaEnabled = configService.selectCaptchaEnabled();
//        if (captchaEnabled) {
//            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
//        }
//
//        if (StringUtils.isEmpty(username)) {
//            msg = "用户名不能为空";
//        } else if (StringUtils.isEmpty(password)) {
//            msg = "用户密码不能为空";
//        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
//                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
//            msg = "账户长度必须在2到20个字符之间";
//        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
//            msg = "密码长度必须在6到10个字符之间";
//        } else if (!userService.checkUserNameUnique(sysUser)) {
//            msg = "保存用户'" + username + "'失败，注册账号已存在";
//        } else {
//            sysUser.setUserId(IdUtil.getSnowflakeNextId());
//            sysUser.setNickName(username);
//            sysUser.setPassword(SecurityUtils.encryptPassword(password));
//            boolean regFlag = userService.registerUser(sysUser);
//            if (!regFlag) {
//                msg = "注册失败,请联系系统管理人员";
//            } else {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
//            }
//        }
//        return msg;
//    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
//    public void validateCaptcha(String username, String code, String uuid) {
//        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
//        String captcha = redisCache.getCacheObject(verifyKey);
//        redisCache.deleteObject(verifyKey);
//        if (captcha == null) {
//            throw new CaptchaExpireException();
//        }
//        if (!code.equalsIgnoreCase(captcha)) {
//            throw new CaptchaException();
//        }
//    }
    @Transactional(rollbackFor = Exception.class)
    public String appRegister(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(), invitationCode = registerBody.getInvitationCode();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            msg = "用户名/密码不能为空";
        } else if (!Validator.isMobile(username)) {
            msg = "输入的手机号有误";
        } else if (!ReUtil.isMatch(Constants.REGEX, password)) {
            msg = "请输入6~10位数字字母密码";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在6到10个字符之间";
        } else if (!userService.checkUserNameUnique(sysUser)) {
            msg = "注册账号已存在";
        } else {
            //校验邀请码
            if (StrUtil.isNotEmpty(invitationCode)) {
                SysUser inviteUser = userService.selectUserByInvitationCode(invitationCode);
                if (ObjUtil.isNull(inviteUser)) {
                    return "邀请人不存在";
                }
                sysUser.setInviterId(inviteUser.getUserId());
            }

            // 验证码开关
            boolean captchaEnabled = configService.selectCaptchaEnabled();
            if (captchaEnabled) {
                SmsUtil.validateCaptcha(username, registerBody.getCode(), registerBody.getBusinessType());
            }

            sysUser.setUserId(IdUtil.getSnowflakeNextId());
            sysUser.setInvitationCode(InvitCodeUtil.generateUniqueInviteCode());
            sysUser.setNickName(Constants.USER_NICK_PREFIX + RandomUtil.randomString(8));
            sysUser.setPhonenumber(username);
            sysUser.setUserType("01");
            sysUser.setChannel(registerBody.getChannel());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                //分配默认角色
                Long[] longs = {2L};
                userService.insertUserAuth(sysUser.getUserId(), longs);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }


//    public void validateCaptcha2(String username, String code, String businessType) {
//        String verifyKey = SmsUtil.setCacheKey(username, businessType);
//        String captcha = redisCache.getCacheObject(verifyKey);
//        if (captcha == null) {
//            throw new CaptchaExpireException();
//        }
//        if (!code.equalsIgnoreCase(captcha)) {
//            throw new CaptchaException();
//        }
//        redisCache.deleteObject(verifyKey);
//    }

    public String forgetPassword(RegisterBody params) {
        String msg = "", username = params.getUsername(), password = params.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (!ReUtil.isMatch(Constants.REGEX, password)) {
            msg = "请输入6~10位数字字母密码";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在6到10个字符之间";
        } else {
            SysUser sys = userService.selectUserByUserName(username);
            if (sys == null) {
                return "用户不存在";
            } else if (UserStatus.DISABLE.getCode().equals(sys.getStatus())) {
                return "账号：" + username + " 异常请联系客服";
            } else if (UserStatus.DELETED.getCode().equals(sys.getStatus())) {
                return "账号：" + username + " 已注销";
            }
            sysUser.setUserId(sys.getUserId());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));

            // 验证码开关
            boolean captchaEnabled = configService.selectCaptchaEnabled();
            if (captchaEnabled) {
                SmsUtil.validateCaptcha(username, params.getCode(), params.getBusinessType());
            }
            int regFlag = userService.resetPwd(sysUser);
            if (regFlag != 1) {
                msg = "修改密码失败,请联系系统管理人员";
            } else {
                // 验证码正确，清除验证码及("密码")错误次数
                redisCache.deleteObject(CacheConstants.PWD_ERR_CNT_KEY + username);
            }
        }
        return msg;
    }

    public String updatePayPwd(String username, String password, String code, String type) {
        String msg = "";
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        if (StringUtils.isEmpty(username)) {
            msg = "手机号不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (!ReUtil.isMatch("^\\d+$", password)) {
            msg = "请输入6位数字密码";
        } else if (password.length() != UserConstants.PASSWORD_MIN_LENGTH) {
            msg = "密码长度必须是6位数字";
        } else {
            SysUser sys = userService.selectUserByUserName(username);
            if (ObjUtil.isNull(sys)) {
                return "用户不存在";
            }
            if (!StrUtil.equals(username, SecurityUtils.getUsername())) {
                return "手机号和绑定账号不一致";
            }
            if (StrUtil.isNotBlank(sys.getPayPwd())) {
                return "已设置过支付密码";
            }
            sysUser.setUserId(sys.getUserId());
            sysUser.setPayPwd(SecurityUtils.encryptPassword(password));
            // 验证码开关
            boolean captchaEnabled = configService.selectCaptchaEnabled();
            if (captchaEnabled) {
                SmsUtil.validateCaptcha(username, code, type);
            }
            int regFlag = userService.resetPwd(sysUser);
            if (regFlag != 1) {
                msg = "修改密码失败,请联系系统管理人员";
            }
        }
        return msg;
    }

    public R changePhone(String userName, String code, String businessType) {
        if (!Validator.isMobile(userName)) {
            return R.fail("手机号格式不正确");
        }
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserById(userId);
        if (StrUtil.equals(userName, user.getUserName())) {
            return R.fail("换绑手机号相同");
        }
        SysUser sys = sysUserMapper.getUserByUserName(userName);
        if (ObjUtil.isNotEmpty(sys)) {
            return R.fail("账号已被注册");
        }
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            SmsUtil.validateCaptcha(userName, code, businessType);
        }
        //换绑
        SysUser res = new SysUser();
        res.setUserId(userId);
        res.setUserName(userName);
        res.setPhonenumber(userName);
        int i = sysUserMapper.updateUser(res);
        if (i != 1) {
            return R.fail("换绑手机号失败");
        }
        return R.ok();
    }
}
